package com.hxl.demo.tools;

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 异常类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * validated 异常返回
     * @param exception
     * @return
     */
    @ExceptionHandler
    public Result validationBodyException(BindException exception) {
        BindingResult result = exception.getBindingResult();
        String msg = null;
        if (result.hasErrors()) {
            List<ObjectError> error = result.getAllErrors();
            for (ObjectError fieldError : error) {
                String errMsg = fieldError.getDefaultMessage();
                if(null == msg) {
                    msg = errMsg;
                }
            }
        }
        return Result.fail().message(msg);
    }
}
